package br.com.pentagrama.service.ui.component;

import java.awt.Container;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.text.ParseException;

import javax.swing.BoxLayout;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.text.MaskFormatter;

import br.com.pentagrama.service.ui.event.IPChangedEvent;

public class IPField implements Field {

	private JFormattedTextField[] parts;

	private IPChangedEvent event;

	private String oldValue;


	private JPanel panel;

	public IPField(int width, int height, IPChangedEvent event) {
		super();

		panel = new JPanel();
		panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
		
		oldValue = "...";
		this.event = event;

		parts = new JFormattedTextField[4];
		for (int i = 0; i < 4; i++) {
			JFormattedTextField part = new JFormattedTextField();
			parts[i] = part;
			part.setHorizontalAlignment(JTextField.CENTER);
			part.addPropertyChangeListener("value",
					new PropertyChangeListener() {

						public void propertyChange(PropertyChangeEvent event) {
							updateValues();
						}
					});
		}
	}

	public void showIn(Container container) {
		try {			
			JFormattedTextField firstPart = parts[0];
			MaskFormatter firstPartMask = new MaskFormatter("###");
			firstPartMask.setAllowsInvalid(false);
			firstPartMask.install(firstPart);
			panel.add(firstPart);
			
			for (int i = 1; i < parts.length; i++) {
				JLabel dot = new JLabel(" . ");
				panel.add(dot);
								
				JFormattedTextField part = parts[i];
				MaskFormatter mask = new MaskFormatter("###");
				mask.setAllowsInvalid(false);
				mask.install(part);
				panel.add(part);
				
			}

		} catch (ParseException e) {
			throw new RuntimeException(e);
		}
		
		container.add(panel);
		event.updateValue(oldValue);
	}
	
	private void updateValues() {		
		String value = parts[0].getText().trim();

		for (int i = 1; i < parts.length; i++) {
			value += "." + parts[i].getText().trim();
		}

		if (!value.equals(oldValue)) {
			event.updateValue(value);
			oldValue = value;
		}
	}
}